package kitwee.com.kanpad.orderDetail;

import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;

import com.kitwee.serialport.util.SimpleCountDownTimer;

import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import kitwee.com.kanpad.BaseActivity;
import kitwee.com.kanpad.BuildConfig;
import kitwee.com.kanpad.R;
import kitwee.com.kanpad.bean.DepartmentInfo;
import kitwee.com.kanpad.bean.DepartmentListAdapter;
import kitwee.com.kanpad.bean.ListDetailBean;
import kitwee.com.kanpad.bean.TaskListBean;
import okhttp3.Call;
import utils.FlavorHelper;
import utils.SPUtils;

/**
 * OrderDetailActivity
 *
 * @author Ganquan
 * @date 2018/1/22
 */

public class OrderDetailActivity extends BaseActivity {

    @BindView(R.id.navigation)
    LinearLayout navigation;
    @BindView(R.id.fl_content)
    FrameLayout flContent;
    @BindView(R.id.detail)
    LinearLayout detail;
    @BindView(R.id.message)
    LinearLayout message;
    @BindView(R.id.bom)
    LinearLayout bom;
    @BindView(R.id.sop)
    LinearLayout sop;
    @BindView(R.id.data)
    LinearLayout data;
    @BindView(R.id.image_detail)
    ImageView imageDetail;
    @BindView(R.id.image_im)
    ImageView imageIm;
    @BindView(R.id.image_bom)
    ImageView imageBom;
    @BindView(R.id.image_sop)
    ImageView imageSop;
    @BindView(R.id.image_data)
    ImageView imageData;
    @BindView(R.id.home_pager)
    TextView homePager;
    @BindView(R.id.change_work)
    TextView changeWork;
    @BindView(R.id.work_people)
    RecyclerView workPeople;
    @BindView(R.id.people)
    RelativeLayout people;
    @BindView(R.id.calculator)
    Button calculator;

    private OrderDetailFragment orderDetailFragment;
    private MessageFragment messageFragment;
    private BomFragment bomFragment;
    private SOPFragment sopFragment;
    private RealTimeDataFragment realTimeDataFragment;
    private CountDownTimer countDownTimer;
    private ChangeWorkFragment changeWorkFragment;
    private String endpoint;


    public static void start(Context context, TaskListBean.RowsBean bean) {
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        intent.setClass(context, OrderDetailActivity.class);

        context.startActivity(intent);
        EventBus.getDefault().post(new TaskDetailEvent(bean));
        rowsBean = bean;

    }

    @Override
    protected void onResume() {
        super.onResume();
//        initDepartment();
//        initTaskDetail();

    }


    /**
     * 交接班人.
     */
    private void initDepartment() {
        String user = SPUtils.getString(this, "user");
        String key = SPUtils.getString(this, "key");
        final long time = System.currentTimeMillis();
        final String digest = new String(Hex.encodeHex(DigestUtils.md5((key + user + time).getBytes())));
        String timer = String.valueOf(time);

        OkHttpUtils.get()
                .tag(this)
//                .url(KanpadStrings.HOSTURL + "/deviceStatusRecords/findUserList")
                .url(endpoint + "/deviceStatusRecords/findUserList")
                .addParams("pun", user)
                .addParams("pd", digest)
                .addParams("t", timer)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        LogUtils.e("交接班联系人 ; " + e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        LogUtils.e("交接班联系人 : " + response);
                        JSONObject jsonObj = JSON.parseObject(response);
                        JSONObject data = jsonObj.getJSONObject("data");
                        JSONArray rows = data.getJSONArray("rows");
                        List<DepartmentInfo.DataBean.RowsBean> departList = JSON.parseArray(rows.toString(), DepartmentInfo.DataBean.RowsBean.class);

                        for (int i = 0; i < departList.size(); i++) {
                            LogUtils.e("开机员............" + departList.get(i).getRole_name() + " ... " + departList.get(i).getName());
                            if (departList.get(i).getRole_name() != null && TextUtils.equals("开机员", departList.get(i).getRole_name())) {
                                departmentList.add(departList.get(i));

                            }
                        }

                    }
                });
    }


    private Timer timer;
    private TimerTask task;
    private static final int TIMED = 1;
    private static final int SUCCESS = 2;

    private void initTaskDetail() {
        initNetData();
        reRequest();
    }

    private void reRequest() {
        countDownTimer = new CountDownTimer(5 * 1000, 1000) {
            @Override
            public void onTick(long l) {

            }

            @Override
            public void onFinish() {
                initNetData();
                reRequest();
            }
        }.start();
    }


    public static TaskListBean.RowsBean rowsBean;

    private void initNetData() {
        if (rowsBean != null) {
            if (!isFinishing()) {
                String task_id = rowsBean.getId();
                String user = SPUtils.getString(this, "user");
                String key = SPUtils.getString(this, "key");
                final long time = System.currentTimeMillis();
                final String digest = new String(Hex.encodeHex(DigestUtils.md5((key + user + time).getBytes())));
                String timer = String.valueOf(time);
                OkHttpUtils.get()
                        .tag(this)
//                        .url(KanpadStrings.HOSTURL + "/productionTask/getProductionTaskDetail")
                        .url(endpoint + "/productionTask/getProductionTaskDetail")
                        .addParams("EQ_task_id", task_id)
                        .addParams("pun", user)
                        .addParams("pd", digest)
                        .addParams("t", timer)
                        .build()
                        .execute(new StringCallback() {

                            @Override
                            public void onError(Call call, Exception e, int id) {
                                e.printStackTrace();
                                LogUtils.e("请求任务详情失败 ：" + call + " ;错误 ：" + e + "; id :" + id);
                            }

                            @Override
                            public void onResponse(String response, int id) {
                                LogUtils.e("请求任务详情成功 : " + response);
                                ListDetailBean listDetailBean = JSON.parseObject(response, ListDetailBean.class);
                                EventBus.getDefault().postSticky(new OrderDetailEvent(listDetailBean));


                            }
                        });
            }
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.order_detail_layout);
        ButterKnife.bind(this);

//
//        workPeople.setLayoutManager(new GridLayoutManager(this, 3));
//        workPeople.setAdapter(departmentListAdapter);
//        departmentListAdapter.setOnItemClickLitener(new DepartmentListAdapter.OnItemClickLitener() {
//            @Override
//            public void onItemClick(View view, int position) {
//                departmentID = departmentList.get(position).getId();
//                departName = departmentList.get(position).getName();
//            }
//        });

        endpoint = BuildConfig.API_ENDPOINT;
        setTabSelection(1);
        setTabSelection(2);
        setTabSelection(3);
        setTabSelection(4);
        setTabSelection(5);
        setTabSelection(0);

//        orderDetailFragment.updateDetail(rowsBean);
        setIcon(imageDetail, R.drawable.icon_detail_chose, imageIm, R.drawable.icon_im_normal, imageBom, R.drawable.icon_bom_normal, imageSop, R.drawable.icon_sop_normal, imageData, R.drawable.icon_data_normal);
//        if (FlavorHelper.isXiongTian()) {
//            // 隐藏返回按钮
//            homePager.setVisibility(View.GONE);
//        }


    }

    private void setTabSelection(int index) {
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        hideFragments(transaction);
        switch (index) {
            case 0:
                if (orderDetailFragment == null) {
                    orderDetailFragment = OrderDetailFragment.newInstance(rowsBean);
                    transaction.add(R.id.fl_content, orderDetailFragment, "orderDetailFragment");
                } else {
                    transaction.show(orderDetailFragment);
                }
                break;
            case 1:
                if (messageFragment == null) {
                    messageFragment = MessageFragment.newInstance();
                    transaction.add(R.id.fl_content, messageFragment, "messageFragment");
                } else {
                    transaction.show(messageFragment);
                }
                break;
            case 2:
                if (bomFragment == null) {
                    bomFragment = BomFragment.newInstance();
                    transaction.add(R.id.fl_content, bomFragment, "bomFragment");
                } else {
                    transaction.show(bomFragment);
                }
                break;
            case 3:
                if (sopFragment == null) {
                    sopFragment = SOPFragment.newInstance();

                    transaction.add(R.id.fl_content, sopFragment, "sopFragment");
                } else {
                    transaction.show(sopFragment);
                }
                break;
            case 4:
                if (realTimeDataFragment == null) {
                    realTimeDataFragment = RealTimeDataFragment.newInstance();
                    transaction.add(R.id.fl_content, realTimeDataFragment, "realFragment");
//                    realTimeDataFragment.setEquipmentID(rowsBean.getUser_equipment_id());
                } else {
                    transaction.show(realTimeDataFragment);
                }
                break;
            case 5:
                if (changeWorkFragment == null) {
                    changeWorkFragment = ChangeWorkFragment.newInstance(rowsBean);
                    transaction.add(R.id.fl_content, changeWorkFragment, "changeWorkFragment");
                } else {
                    transaction.show(changeWorkFragment);
                }
                break;

        }
        transaction.commit();
    }


    private void hideFragments(FragmentTransaction transaction) {
        if (orderDetailFragment != null) {
            transaction.hide(orderDetailFragment);
        }

        if (messageFragment != null) {
            transaction.hide(messageFragment);
        }
        if (bomFragment != null) {
            transaction.hide(bomFragment);
        }

        if (sopFragment != null) {
            transaction.hide(sopFragment);
        }
        if (realTimeDataFragment != null) {
            transaction.hide(realTimeDataFragment);
        }
        if (changeWorkFragment != null) {
            transaction.hide(changeWorkFragment);
        }
    }

    private void succession(String id) {
        String user = SPUtils.getString(this, "user");
        String key = SPUtils.getString(this, "key");
        final long time = System.currentTimeMillis();
        final String digest = new String(Hex.encodeHex(DigestUtils.md5((key + user + time).getBytes())));
        String timer = String.valueOf(time);
        OkHttpUtils.get()
                .tag(this)
//                .url(KanpadStrings.HOSTURL + "/deviceStatusRecords/stopTask")
                .url(endpoint + "/deviceStatusRecords/stopTask")
                .addParams("pun", user)
                .addParams("pd", digest)
                .addParams("t", timer)
                .addParams("leader_name", id)
                .addParams("task_id", rowsBean.getId())
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        LogUtils.e("换班失败 ; " + e.getMessage());
                        ToastUtils.showShort("换班失败,请重试");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        JSONObject jsonObj = JSON.parseObject(response);
                        String data = jsonObj.getString("statusCode");
                        if (TextUtils.equals("200", data)) {
                            LogUtils.e("换班成功 ; " + response);
                            finish();
                        } else {
                            LogUtils.e("换班失败 ; " + jsonObj.getString("message"));
                            ToastUtils.showShort("换班失败,请重试");
                        }

                    }
                });


    }

    private String departmentID;
    private String departName;

    @OnClick({R.id.detail, R.id.message, R.id.bom, R.id.sop, R.id.data, R.id.home_pager
            , R.id.change_work, R.id.cancel, R.id.tv_sure, R.id.calculator})
    public void onClick(View view) {
        switch (view.getId()) {
            //计算器
            case R.id.calculator:
//                Intent intent = new Intent();
//                intent.setClassName("com.android.calculator2", "com.android.calculator2.Calculator");
//                startActivity(intent);
                break;
            case R.id.change_work://转班
                setTabSelection(5);
//                flContent.setVisibility(View.GONE);
//                people.setVisibility(View.VISIBLE);
//                setRecycleView();
                break;
//            case R.id.cancel:
//                people.setVisibility(View.GONE);
//                flContent.setVisibility(View.VISIBLE);
//                break;
//            case R.id.tv_sure:
//                succession(departmentID);
//
//                people.setVisibility(View.GONE);
//                break;
            case R.id.home_pager:
                finish();
                break;
            case R.id.detail:
                setTabSelection(0);
                setIcon(imageDetail, R.drawable.icon_detail_chose, imageIm, R.drawable.icon_im_normal, imageBom, R.drawable.icon_bom_normal, imageSop, R.drawable.icon_sop_normal, imageData, R.drawable.icon_data_normal);
                break;
            case R.id.message:
                setTabSelection(1);
                setIcon(imageDetail, R.drawable.icon_detail_normal, imageIm, R.drawable.icon_im_chose, imageBom, R.drawable.icon_bom_normal, imageSop, R.drawable.icon_sop_normal, imageData, R.drawable.icon_data_normal);
                break;
            case R.id.bom:
                setTabSelection(2);
                setIcon(imageDetail, R.drawable.icon_detail_normal, imageIm, R.drawable.icon_im_normal, imageBom, R.drawable.icon_bom_chose, imageSop, R.drawable.icon_sop_normal, imageData, R.drawable.icon_data_normal);
                break;
            case R.id.sop:
                setTabSelection(3);
                setIcon(imageDetail, R.drawable.icon_detail_normal, imageIm, R.drawable.icon_im_normal, imageBom, R.drawable.icon_bom_normal, imageSop, R.drawable.icon_sop_chose, imageData, R.drawable.icon_data_normal);
                break;
            case R.id.data:
                setTabSelection(4);
                setIcon(imageDetail, R.drawable.icon_detail_normal, imageIm, R.drawable.icon_im_normal, imageBom, R.drawable.icon_bom_normal, imageSop, R.drawable.icon_sop_normal, imageData, R.drawable.icon_data_chose);
                break;
        }
    }

    private List<DepartmentInfo.DataBean.RowsBean> departmentList = new ArrayList<>();
    private DepartmentListAdapter departmentListAdapter = new DepartmentListAdapter();

    private void setRecycleView() {

        departmentListAdapter.setData(departmentList);

        departmentListAdapter.notifyDataSetChanged();


    }

    private void setIcon(ImageView imageDetail, int icon_detail_chose, ImageView imageIm, int icon_im_normal, ImageView imageBom, int icon_bom_normal, ImageView imageSop, int icon_sop_normal, ImageView imageData, int icon_data_normal) {
        updateIcon(imageDetail, icon_detail_chose);
        updateIcon(imageIm, icon_im_normal);
        updateIcon(imageBom, icon_bom_normal);
        updateIcon(imageSop, icon_sop_normal);
        updateIcon(imageData, icon_data_normal);
    }


    private void updateIcon(ImageView a, int icon) {
        a.setImageResource(icon);
    }

    private List<Character> mChars = new ArrayList<>();

    private CountDownTimer mTimer = new SimpleCountDownTimer(500) {

        @Override
        public void onFinish() {
            StringBuilder builder = new StringBuilder();
            for (char ch : mChars) {
                builder.append(ch);
            }
            String result = builder.toString();
            EventBus.getDefault().post(new ScannerEvent(result));
            Log.d("Scanner", "扫描结果: " + result);
            mChars.clear();
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        mTimer.cancel();
        switch (keyCode) {
            case KeyEvent.KEYCODE_SHIFT_LEFT:
            case KeyEvent.KEYCODE_SHIFT_RIGHT:
                break;
            default:
                mChars.add((char) event.getUnicodeChar());
                break;
        }
        mTimer.start();
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }


    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);

    }

    @Subscribe
    public void onShowMessageEvent(OrderRequest orderRequest) {
//        initNetData();
    }


    @Subscribe
    public void onShowCancleEvent(ChangeWorkEvent event) {
        setTabSelection(0);
        setIcon(imageDetail, R.drawable.icon_detail_chose, imageIm, R.drawable.icon_im_normal,
                imageBom, R.drawable.icon_bom_normal, imageSop, R.drawable.icon_sop_normal,
                imageData, R.drawable.icon_data_normal);
    }
}
